# -*- encoding=utf8 -*-

__author__ = "code哥"
import sys
import os
import time
from conn_pool import get_redis, REDIS_APP_RUN_LOG

rs = get_redis()


class Tail(object):
    def __init__(self, tailed_file):

        self.check_file_validity(tailed_file)
        self.tailed_file = tailed_file
        self.callback = sys.stdout.write

        self.register_callback(print_log)
        self.follow(s=1)

    def follow(self, s=1):

        with open(self.tailed_file) as file_:
            # Go to the end of file
            file_.seek(0, 2)
            while True:
                curr_position = file_.tell()
                line = file_.readline()
                if not line:
                    file_.seek(curr_position)
                    time.sleep(s)
                else:
                    self.callback(line)

    def register_callback(self, func):
        self.callback = func

    def check_file_validity(self, file_):
        if not os.access(file_, os.F_OK):
            raise TailError("File '%s' does not exist" % (file_))
        if not os.access(file_, os.R_OK):
            raise TailError("File '%s' not readable" % (file_))
        if os.path.isdir(file_):
            raise TailError("File '%s' is a directory" % (file_))


class TailError(Exception):
    def __init__(self, msg):
        self.message = msg

    def __str__(self):
        return self.message


def print_log(msg):
    rs.rpush(REDIS_APP_RUN_LOG, msg)
    # 保存最新500条
    rs.ltrim(REDIS_APP_RUN_LOG, 0, 500 - 1)


def main():
    Tail('{path}/run.log'.format(path=os.path.dirname(os.path.abspath(__file__))))


if __name__ == '__main__':
    main()
